package com.muzi.factory;

import com.muzi.observer.Observer;
import com.muzi.state.FaultyState;
import com.muzi.state.IdleState;
import com.muzi.state.MachineState;
import com.muzi.state.WorkingState;
import com.muzi.strategy.BalancedPathStrategy;
import com.muzi.strategy.DangerPathStrategy;
import com.muzi.strategy.EfficientPathStrategy;
import com.muzi.strategy.PathPlanningStrategy;

public class Seeder implements FarmEquipment , Observer {
    @Override
    public void operate() {
        System.out.println("播种机正在运行。");
    }

    //策略模式
    private PathPlanningStrategy strategy;

    // 根据土壤湿度自动选择策略
    public void setStrategyByMoistureLevel(double moisture) {
        if (moisture < 30) {
            this.strategy = new EfficientPathStrategy(); //高效路径
        } else if (moisture < 70) {
            this.strategy = new BalancedPathStrategy(); //平衡路径
        } else {
            this.strategy = new DangerPathStrategy(); //危险路径
        }
    }

    public void executeStrategy() {
        if (strategy != null) {
            strategy.planPath();
        } else {
            System.out.println("未设置路径规划策略！");
        }
    }


    // 观察者模式
    private String name;

    public void update(String message) {
        System.out.println(name + " 收到通知: " + message);
    }


    //状态模式
    private MachineState state;

    public Seeder() {
        this.state = new IdleState(); // 初始为空闲状态
        this.state.onEnter(this);
    }

    public Seeder(String name) {
        this.name = name;
    }

    public void setState(MachineState state) {
        this.state = state;
        this.state.onEnter(this); // 调用新状态的进入方法
    }

    /**
     * 手动切换状态（根据传入的字符串参数）
     */
    public void changeState(String targetState) {
        switch (targetState.toLowerCase()) {
            case "idle":
                setState(new IdleState());
                break;
            case "working":
                setState(new WorkingState());
                break;
            case "faulty":
                setState(new FaultyState());
                break;
            default:
                System.out.println("未知状态: " + targetState);
                break;
        }
    }

    /**
     * 获取当前状态名称
     */
    public String getCurrentState() {
        if (state instanceof IdleState) return "idle";
        if (state instanceof WorkingState) return "working";
        if (state instanceof FaultyState) return "faulty";
        return "unknown";
    }

}
